<?php

	class manga_chapter_model extends st_model {
		protected $_instance  = array(
										  'table'      => 'catalog_manga_chapter', 
										  'primaryKey' => 'id',
									  );
									  
		public function getChapterUrl() 
		{
			return site_url('admin/catalog/chapter/edit/id/' . $this->getId(), true);
		}
		
		public function getIndexUrl($param = '') 
		{
			return site_url() . '/admin/catalog/chapter/index/' . $param;
		}
		
		public function getManga() 
		{
			if (!$this->isLoaded()) {
				return null;
			}
			$this->load->model('manga_model');
			$this->manga_model->loadByPK($this->getMangaId());
			return $this->manga_model;			
		}
		
		public function getChapterReferences()
		{
			if (!$this->isLoaded()) {
				return array();
			}
			if ($manga = $this->getManga()) {
				$collection = $manga->getChapterCollection();
				if (!$collection) {
					return array();
				}
				return $collection;
			}
			return array();
		}
		
		public function parseArrayToPageIndexers($pages)
		{
			foreach ($pages as $key => $page) {
				if (strlen($page['number']) == 0) {
					unset($pages[$key]);
				}
			}
			return json_encode($pages);
		}
		
		public function getPages()
		{
			if (!$this->isLoaded()) {
				return array();
			}
			$jsonPages = $this->getPageIndexes();
			$pages = json_decode($jsonPages, true);
			if (!is_array($pages)) {
				return array();
			}
			uasort($pages, 'comparePageIndex');
			return $pages;
		}
	}	
?>
<?php 
	function comparePageIndex($page1, $page2) {
		$a = (integer)$page1['number'];
		$b = (integer)$page2['number'];
	    if ($a == $b) {
	        return 0;
	    }
	    return ($a < $b) ? -1 : 1;
	}
?>